package com.my.demo.controller.personal;

import com.my.demo.pojo.FamilyInformation;
import com.my.demo.pojo.PerIdentify;
import com.my.demo.pojo.Result;
import com.my.demo.pojo.UploadLog;
import com.my.demo.service.FamilyInformationService;
import com.my.demo.service.PerIdentifyService;
import com.my.demo.service.UploadLogService;
import com.my.demo.service.UserService;
import com.my.demo.utils.OCR;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
//上传文件的Controller
public class FileUploadController {

  @Autowired
  FamilyInformationService familyInformationService;
  @Autowired
  PerIdentifyService perIdentifyService;
  @Autowired
  OCR ocr;
  @Autowired
  UploadLogService uploadLogService;
  @Autowired
  UserService userService;


  String path = System.getProperty("user.dir")+"\\family_archives";
  float scale = 2.5f;// 缩放比例
  float rotation = 0f;// 旋转角度

  public FileUploadController() throws FileNotFoundException {
  }


  /*
   * 上传要识别的家谱文件，上传之后自动开启OCR识别
   */
//  @PostMapping("/old_upload")
//  public Result old_upload(@RequestParam("genealogyFiles") MultipartFile[] genealogyFiles, @RequestParam("name") String name,
//                       HttpSession session) throws IOException {
//    Result result = new Result();
//    result.setSuccess(false);
//    result.setDetail(null);
//    if (genealogyFiles.length > 0) {
//      String dir_path = path + "\\" + name;
//      File dir = new File(dir_path);
//      if (!dir.exists()) {
//        dir.mkdir();
//      } else {
//        result.setMsg("家谱已经存在");
//        return result;
//      }
//      //家谱信息的录入
//      Integer userId = (Integer) session.getAttribute("id");
//      FamilyInformation familyInformation = new FamilyInformation(name, userId, genealogyFiles.length);
//      familyInformationService.save(familyInformation);
//      Integer familyInformationFamilyArchiveId = familyInformation.getFamilyArchiveId();
//
//
//      for (int i = 0; i < genealogyFiles.length; i++) {
//        MultipartFile genealogyFile = genealogyFiles[i];
//        if (!genealogyFile.isEmpty()) {
//          String originalFilename = genealogyFile.getOriginalFilename();
//          String last_path = (dir_path + "\\" + (i + 1) + getFormat(originalFilename));
//          genealogyFile.transferTo(new File(last_path));
//          //将图片信息录入
//          PerIdentify perIdentify = new PerIdentify(familyInformationFamilyArchiveId, (i + 1), "/family_archives/" + name + "/" + (i + 1) + getFormat(originalFilename));
//          perIdentifyService.save(perIdentify);
//        }
//      }
//
//      result.setSuccess(true);
//      result.setMsg("上传成功");
//
//      //开启识别任务
//      System.out.println(familyInformationFamilyArchiveId);
//      ocr.run(familyInformationFamilyArchiveId);
//
//      //添加上传记录
//      UploadLog uploadLog = new UploadLog(null, null, familyInformationFamilyArchiveId, userId);
//      uploadLogService.save(uploadLog);
//
//    }
//
//    return result;
//  }
//  public String getFormat(String originalFilename) {
//    String[] split = originalFilename.split("\\.");
//
//    return "." + split[split.length - 1];
//  }


  @PostMapping("/upload")
  public Result upload(@RequestParam("genealogyFiles") MultipartFile[] genealogyFiles,
      @RequestParam("name") String name
      ) throws Exception {
    Result result = new Result();
    result.setSuccess(false);
    result.setDetail(null);
    if (genealogyFiles.length > 0) {
      String dir_path = path + "\\" + name;
      File dir = new File(dir_path);
      if (!dir.exists()) {
        dir.mkdir();
      } else {
        result.setMsg("家谱已经存在");
        return result;
      }

      //家谱信息的录入
      String userName = (String) SecurityUtils.getSubject().getPrincipal();
      Integer userId = userService.selectIdByName(userName);

      FamilyInformation familyInformation = new FamilyInformation(name, userId,
          genealogyFiles.length,0);

      familyInformationService.save(familyInformation);

      Integer familyInformationFamilyArchiveId = familyInformation.getFamilyArchiveId();

      Integer index = 1;
      for (int i = 0; i < genealogyFiles.length; i++) {
        MultipartFile genealogyFile = genealogyFiles[i];
        String fileName = genealogyFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("文件名称：" + fileName + ",文件后缀：" + suffix);
        if ("jpg".equals(suffix) || "png".equals(suffix)) {
          String last_path = (dir_path + "\\" + index + "." + suffix);
          genealogyFile.transferTo(new File(last_path));
          System.out.println(fileName + "已经保存");

          //将图片信息录入
          PerIdentify perIdentify = new PerIdentify(familyInformationFamilyArchiveId, index,
              "/family_archives/" + name + "/" + index + "." + suffix);
          perIdentifyService.save(perIdentify);
          index++;

        } else if ("pdf".equals(suffix)) {
          Document document = new Document();
          document.setByteArray(genealogyFile.getBytes(), 0, genealogyFile.getBytes().length, fileName);
          Integer pageName = document.getNumberOfPages();
          System.out.println("PDF页数：" + pageName);
          for (int j = 0; j < pageName; j++) {
            BufferedImage image = (BufferedImage) document
                .getPageImage(j, GraphicsRenderingHints.SCREEN,
                    org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;
            try {
              File new_file = new File(dir_path + "\\" + (index) + ".jpg");
              ImageIO.write(rendImage, "jpg", new_file);
            } catch (IOException e) {
              e.printStackTrace();
            }
            image.flush();

            //将图片信息录入
            PerIdentify perIdentify = new PerIdentify(familyInformationFamilyArchiveId, index,
                "/family_archives/" + name + "/" + index + ".jpg" );
            perIdentifyService.save(perIdentify);
            index++;
          }
          System.out.println(fileName + "已经保存");

        } else {
          System.out.println(fileName + "不支持保存");
        }



      }
      result.setSuccess(true);
      result.setMsg("上传成功");
      //更新页码数
      familyInformation.setTotalPages(index-1);
      familyInformationService.updateById(familyInformation);
      //开启识别任务
      System.out.println(familyInformationFamilyArchiveId);
      ocr.run(familyInformationFamilyArchiveId);

      //添加上传记录
      UploadLog uploadLog = new UploadLog(null, null, familyInformationFamilyArchiveId, userId);
      uploadLogService.save(uploadLog);
    }

    return result;
  }
}
//  private Integer generateFile(MultipartFile file,Integer index,String dir_path) throws Exception {
//    String fileName = file.getOriginalFilename();
//    Document document = new Document();
//    document.setByteArray(file.getBytes(), 0, file.getBytes().length, fileName);
//    Integer pageName=document.getNumberOfPages();
//    System.out.println("PDF页数：" + pageName);
//    for (int i = 0; i < pageName; i++) {
//      BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN,
//          org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
//      RenderedImage rendImage = image;
//      try {
//        File new_file = new File(dir_path + "\\"+(index+i) + ".jpg");
//        ImageIO.write(rendImage, "jpg", new_file);
//      } catch (IOException e) {
//        e.printStackTrace();
//      }
//      image.flush();
//
//      //将图片信息录入
//      PerIdentify perIdentify = new PerIdentify(familyInformationFamilyArchiveId, index, "/family_archives/" + name + "/" + index+"."+suffix);
//      perIdentifyService.save(perIdentify);
//
//    }
//    return pageName;
//  }


